package com.chen.demozuul.fallback;


import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 网关容错
 */
@Component
public class DemoFallback implements FallbackProvider {

    @Override
    public String getRoute() {
       // return "服务名";
        return "*"; //*代表所有服务
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse(){
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                String response = "{\n" +
                        "    \"msg\": \"服务失去联系,请联系管理员"+cause+"\",\n" +
                        "    \"code\": 400,\n" +
                        "    \"data\": null\n" +
                        "}";
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(response.getBytes());
                return byteArrayInputStream;
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                return httpHeaders;
            }
        };
    }
}
